package com.lly.pro.service;

import com.lly.pro.common.ParamterCheckUtil;
import com.lly.pro.common.Tools;
import com.lly.pro.entity.HR;
import com.lly.pro.repositories.HRRepository;
import com.xiaoleilu.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Service
public class HRService {
    @Autowired
    private HRRepository hrRepository;
    @PersistenceContext
    private EntityManager em;

    @Transactional( rollbackFor = Exception.class)
    public HR save(HR hr){
        return hrRepository.save(hr);
    }

    public Integer findByUserNameAndPassword(String userName,String password){
        return hrRepository.findByUserNameAndPassword(userName,password);
    }

    public List<HR> findByDepartment(String department){
        String sql = String.format("SELLECT * FROM hr WHERE department={0}", department);
        Query query = em.createQuery(sql);
        List<HR> hrList = query.getResultList();
        return hrList;
    }

    public String HRSQLBuildeer(JSONObject param){
        StringBuffer sql = new StringBuffer("FROM com.lly.pro.entity.HR");
        boolean flag = false;
        if (ParamterCheckUtil.isContainTargetParams(HR.class,param)){
            sql.append(" WHERE");
            for (String attr:param.keySet()) {
                if (flag){
                    sql.append(" AND");
                }
                sql.append(" "+ Tools.changeAttrToColumn(attr)+"="+param.get(attr));
                flag = true;
            }
        }
        return sql.toString();
    }

    public List<HR> unionQuery(JSONObject param){
        Query query = em.createQuery(HRSQLBuildeer(param));
        List<HR> result = null;
        try{
            result = query.getResultList();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return result;
        }
    }

    public List<HR> findAll() {
        return hrRepository.findAll();
    }

    public HR findByUserId(long userId) {
        return hrRepository.findByUserId(userId);
    }

    public List findUserIdByUserNameAndPassword(String userName,String password){
        return hrRepository.findUserId(userName,password);
    }

    public long findByUserIdAndPassword(Long userId, String password) {
        return hrRepository.findByUserIdAndPassword(userId,password);
    }
}
